package com.oocl.scanner.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.oocl.exception.ParameterErrorException;
import com.oocl.pojo.Customer;
import com.oocl.scanner.Scanner;

/**
 * 扫描器，包括清洗数据
 * @author GANAB
 *
 */
public class ScannerImpl implements Scanner {
	// ID格式
	private final String ID_REX = "\\d+";
	private final String NAME_REX = "[a-zA-Z\u4e00-\u9fa5]+";
	private final String EMAIL_REX = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$";
	private final String SEX_REX = "true|false";
	private final String BIRTHDAY_REX = "^\\d{4}(\\-|\\/)[01]+?[0-9]*\\1[0-3]+?[0-9]$";
	private InputStream in = null;
	
	public ScannerImpl(InputStream in) {
		this.in = in;
	}

	public List<Customer> scan() throws Exception {
		System.out.println("正在读取并清洗数据……");
		if(in==null){
			throw new Exception("Can not found file.");
		}
		List<Customer> customerList = new ArrayList<Customer>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(in));
			String str = "";
			while((str=br.readLine())!=null){
				Customer customer = clean(str);
				if(customer!=null){
					customerList.add(customer);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			br.close();
		}
		return customerList;
	}

	private Customer clean(String t) throws ParameterErrorException {
		if (t != null) {
			t = t.trim();
			String[] fields = t.split(" ");
			// 去除空格和Tab符
			for (int i = 0; i < fields.length; i++) {
				fields[i] = fields[i].trim();
			}
			// 判断是否为5个，否则抛出异常
			if (fields.length != 5) {
				throw new ParameterErrorException(
						"Customer参数不足，请检查是否满足id name email sex birthday格式");
			}
			// 校验格式，不满足返回null
			if (!fields[0].matches(ID_REX)
					|| !fields[1].matches(NAME_REX)
					|| !fields[2].matches(EMAIL_REX)
					|| !fields[3].matches(SEX_REX)
					|| !fields[4].matches(BIRTHDAY_REX)) {
				return null;
			}

			Customer customer = new Customer();
			customer.setId(fields[0]);
			customer.setName(fields[1]);
			customer.setEmail(fields[2]);
			customer.setSex(("true".equals(fields[3])) ? "boy" : "girl");
			customer.setBirthday(birthdayFormat(fields[4]));

			return customer;
		}

		return null;
	}
	
	private String birthdayFormat(String s){
		return s.replace("/", "-");
	}

}
